package cn.moziware.falldetectordemo;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import cn.moziware.falldetectordemo.databinding.ActivityTestBinding;

public class TestActivity extends AppCompatActivity {
    ActivityTestBinding binding;
    Handler handler = new Handler(Looper.getMainLooper());
    long COUNTDOWN_DELAY = 1000L;
    int COUNTDOWN_START = 10;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityTestBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        binding.buttonYes.setOnClickListener(view -> sendAlert());
        binding.buttonCancelHelp.setOnClickListener(view -> finish());
    }

    @Override
    protected void onResume() {
        super.onResume();
        float force = getIntent().getFloatExtra("force", -1F);
        Log.w("tattoo", "Received fall alert with force " + force);
        handler.removeCallbacksAndMessages(null);
        updateCountdown(COUNTDOWN_START);
    }

    @Override
    protected void onPause() {
        super.onPause();
        handler.removeCallbacksAndMessages(null);
    }

    private void updateCountdown(int timeLeft) {
        if (timeLeft == 0) {
            sendAlert();
            return;
        }
        binding.textTimeout.setText(getString(R.string.timeout_message, timeLeft));
        handler.postDelayed(() -> updateCountdown(timeLeft -1 ), COUNTDOWN_DELAY);
    }

    private void sendAlert() {
        Toast.makeText(this, R.string.toast_message, Toast.LENGTH_SHORT).show();
        finish();
    }
}